package chapter03;

import java.util.NoSuchElementException;

public class SingleQueue<E> {

    private Node<E> front, rear;

    public SingleQueue() {
        this(null, null);
    }

    public SingleQueue(Node<E> front, Node<E> rear) {
        this.front = front;
        this.rear = rear;
    }

    /**
     * 入队
     * @param e
     */
    void enqueue(E e) {
        Node<E> p = new Node<>(e, null);
        //首次
        if (rear == null) {
            rear = p;
            front = p;
        }else {
            rear.next = p;
            rear = rear.next;
        }
    }

    /**
     * 出队
     * @return
     */
    E dequeue() {
        if (front == null) {
            throw new NoSuchElementException();
        }
        E item = front.item;

        if (front.next == null) {
            rear = null;
            front = null;
        }else {
            front = front.next;
        }
        return item;
    }

    /**
     * 内部节点
     * @param <E>
     */
    private class Node<E> {
        E item;
        Node next;

        public Node() {
            this(null);
        }

        public Node(E item) {
            this(item, null);
        }

        public Node(E item, Node next) {
            this.item = item;
            this.next = next;
        }
    }

}
